<template>
	<view>
		<view class="loading-container" v-if="loading">
			<view class="loading-spinner"></view>
			<view class="loading-text">{{ message }}</view>
		</view>

		<view class="container">
			<view class="progress-box" v-if="progress > 0">
				<!-- 进度条 -->
				<progress :percent="progress" stroke-width="4" />
			</view>

			<!-- 数据展示区域 -->
			<view v-if="dataLoaded">
				<!-- 在这里展示加载后的数据 -->
				<image :src="imageUrl" mode="widthFix" class="main-image" />
				<view class="thumbnails">
					<image v-for="(thumbnail, index) in thumbnails" :key="index" :src="thumbnail"
						:class="{ active: selectedThumbnail === index }" @click="selectThumbnail(index)" />
				</view>

				<view class="container_btn">
					<!-- 功能按钮区域 -->
					<view class="function-bar">
						<view class="function-btn" v-for="(item, index) in functionList" :key="index"
							@click="handleFunctionClick(item.key)">
							<uni-icons :type="item.icon"
								:color="((activeKey === item.key) && (collectCnt % 2 === 1)) ? '#ffffff' : '#cacaca'"
								size="25"></uni-icons>
							<!-- <text class="btn-text" :style="{ color: activeKey === item.key ? '#fff' : '#ddd' }">{{ item.text }}</text> -->
						</view>
					</view>
				</view>

				<!-- 更多功能列表 -->
				<view class="more-list" v-if="showMoreList">
					<view class="list-item" @click="handleMoreItemClick('rename')">重命名</view>
					<view class="list-item" @click="handleMoreItemClick('detail')">详情</view>
					<view class="list-item" @click="handleMoreItemClick('rename')">重命名</view>
					<view class="list-item" @click="handleMoreItemClick('detail')">详情</view>
					<view class="list-item" @click="handleMoreItemClick('rename')">重命名</view>
					<!-- ... 其他功能 -->
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import pageJson from "@/pages.json"
	import createSocket from "../../../comfyui/websocket"
	import {
		store
	} from "../../../uni_modules/uni-id-pages/common/store";
	let socket = null; // 将 WebSocket 实例放在模块作用域中

	export default {
		data() {
			return {
				typeMode: '0',
				message: '创作中...', // 自定义加载中文本
				loading: true,

				imageUrl: '',
				thumbnails: [],
				selectedThumbnail: 0,
				progress: 0,
				dataLoaded: false,

				collectCnt: 0,
				collectCnts: [],

				shareImgIds: [],

				topPosition: '180px', // 功能栏距离顶部距离
				moreListTopPosition: '400px', // 功能栏距离顶部距离
				activeKey: '', // 当前激活的功能键
				showMoreList: false, // 是否显示更多功能列表
				functionList: [{
						key: 'undo',
						text: '返回',
						icon: 'undo'
					},
					{
						key: 'collect',
						text: '收藏',
						icon: 'star'
					},
					{
						key: 'download',
						text: '保存',
						icon: 'download'
					},
					// {
					// 	key: 'share',
					// 	text: '转发',
					// 	icon: 'redo'
					// },
					// {
					// 	key: 'more',
					// 	text: '更多',
					// 	icon: 'more'
					// },
				],
			};
		},
		onLoad() {
			// 获取从上一个页面传递过来的 eventChannel 对象
			const eventChannel = this.getOpenerEventChannel();

			// 监听从上一个页面传递过来的数据
			eventChannel.on('socketInfo', (data) => {
				// 根据传递过来的数据进行操作，例如重新初始化 socket 对象
				const client_id = data.client_id;
				// 使用 client_id 初始化 socket 对象，或者根据需要进行其他操作
			});

			// 监听从上一个页面传递过来的数据
			eventChannel.on('collectPageData', (data) => {
				console.log(data)
				this.loading = false;
				//隐藏进度条
				this.progress = 0;
				//页面加载图片
				this.dataLoaded = true;

				this.typeMode = '1';
				this.activeKey = this.functionList[1].key;
				this.selectedThumbnail = 0;
				this.thumbnails = [...this.thumbnails, data.data.fileUrl];
				this.collectCnts = [...this.collectCnts, 1];
				this.imageUrl = this.thumbnails[0];
				this.collectCnt = this.collectCnts[0];

				let shareImgId = {
					idx: this.selectedThumbnail,
					id: data._id
				}
				this.shareImgIds.push(shareImgId);
			});

			socket = createSocket('https://ms724859lw2.vicp.fun', {
				reconnection: true, // 启用重连
				reconnectionDelay: 1000, // 重连间隔时间
				reconnectionAttempts: Infinity, // 重连次数
				transports: ['websocket'], // 仅使用WebSocket传输
			});

			//接收消息
			socket.on('message', (rdata) => {
				console.log(rdata);
				let {
					type,
					data
				} = JSON.parse(rdata);
				if (type === "progress") {
					//进度
					this.progress = (100 / data.max) * data.value;

					//开始画图
					this.loading = false;
					console.log(this.progress);
				}

				//图片生成完成
				if (type === "executed") {
					//取数据
					let get_images = data.output.images;

					//循环生成的数组
					for (let [key, value] of Object.entries(get_images)) {
						let imageurl =
							`http://ms724859lw2.vicp.fun/view?type=${value.type}&subfolder=${value.subfolder}&filename=${value.filename}`;

						this.thumbnails = [...this.thumbnails, imageurl];
						this.collectCnts = [...this.collectCnts, 0];

						console.log(imageurl)
					}

					//默认显示第1张图片
					this.imageUrl = this.thumbnails[0];
					this.collectCnt = this.collectCnts[0];

					//隐藏进度条
					this.progress = 0;

					//页面加载图片
					this.dataLoaded = true;
				}
			})
		},

		methods: {
			selectThumbnail(index) {
				this.selectedThumbnail = index;
				this.imageUrl = this.thumbnails[index];
				this.collectCnt = this.collectCnts[index];
			},

			handleFunctionClick(key) {
				this.activeKey = key;
				if (key === 'more') {
					this.showMoreList = !this.showMoreList;
				} else {
					this.showMoreList = false;
					// 根据key执行相应操作
					switch (key) {
						case 'undo':
							this.handleUndo(this.typeMode);
							break;
						case 'download':
							this.handleSave();
							break;
						case 'collect':
							//判断是否登录，只能登录后才可以执行，否则跳转登录页面
							if (!store.hasLogin) {
								uni.navigateTo({
									url: "/" + pageJson.uniIdRouter.loginPage
								})
							}
							this.collectCnts[this.selectedThumbnail] += 1;
							this.collectCnt = this.collectCnts[this.selectedThumbnail];
							this.handleShare(this.selectedThumbnail);
							break;
					}
				}
			},
			handleMoreItemClick(key) {
				this.showMoreList = false;
				// 根据key执行相应操作
				switch (key) {
					case 'rename':
						this.handleRename();
						break;
					case 'detail':
						this.handleDetail();
						break;
				}
			},
			handleUndo(type) {
				// 执行删除图片操作
				this.thumbnails = [];
				this.imageUrl = '';

				if (type === '0') {
					//跳转创作页面
					uni.navigateTo({
						url: '/pages/create/txt2img_create'
					});
				} else {
					//跳转个人中心页面
					uni.switchTab({
						url: '/pages/ucenter/ucenter'
					})
				}
			},

			handleSave() {
				uni.showLoading({
					title: '保存中',
				});

				// 执行保存图片到本地相册操作
				uni.downloadFile({
					url: this.imageUrl,
					success: (res) => {
						if (res.statusCode === 200) {
							uni.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success: function() {
									uni.hideLoading();
									uni.showToast({
										title: "保存成功",
									});
								},
								fail: function(err) {
									uni.hideLoading();
									uni.showToast({
										title: "保存失败",
									});
								}
							});
						}
					},
					fail: (err) => {
						uni.hideLoading();
					}
				})
			},

			handleShare(n) {
				// 执行分享操作
				if (this.collectCnt % 2 == 1) {
					uni.showToast({
						title: '收藏成功'
					});
					this.handleUpImg(n);
				} else {
					uni.showToast({
						title: '取消收藏'
					});

					this.handleDeleteImg(n);
				}
			},

			handleRename() {
				// 执行重命名操作
			},
			handleDetail() {
				// 执行查看详情操作
			},

			handleDeleteImg(n) {
				let Id = this.shareImgIds.filter(item => item.idx === n);
				let _id = Id[0].id;

				this.shareImgIds.map((item, index) => {
					if (item.idx === n)
						this.shareImgIds.splice(index, 1)
				});

				uniCloud.callFunction({
					name: "share_img_delete",
					data: {
						id: _id,
					}
				}).then(res => {
					console.log('handleDeleteImg success')
				})
			},

			handleUpImg(n) {
				let that = this;
				uniCloud.callFunction({
					name: "share_img_upload",
					data: {
						id: store.userInfo._id,
						time: Date.now(),
						title: "1",
						fileUrl: this.imageUrl
					},
					success(res) {
						console.log(res)
						let shareImgId = {
							idx: n,
							id: res.result.id
						}
						that.shareImgIds.push(shareImgId);

						console.log('handleUpImg success')
					},
					fail() {
						console.log('handleUpImg fail')
					}
				})
			},
		},
	};
</script>

<style>
	.loading-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 100vh;
	}

	.loading-spinner {
		width: 40px;
		height: 40px;
		border-radius: 50%;
		border: 4px solid #f3f3f3;
		border-top: 4px solid #3498db;
		animation: spin 1s linear infinite;
	}

	.loading-text {
		margin-top: 10px;
		font-size: 16px;
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	.container {
		background-color: #f5f5f5;
		padding: 20rpx;
	}

	.main-image {
		width: 100%;
		height: 300rpx;
		margin-bottom: 20rpx;
	}

	.thumbnails {
		display: flex;
		flex-wrap: wrap;
		margin-bottom: 20rpx;
		justify-content: center;
		align-items: center;
	}

	.thumbnails image {
		width: 20%;
		height: 150rpx;
		margin-right: 2%;
		margin-bottom: 2%;
	}

	.thumbnails image.active {
		border: 2rpx solid #007aff;
	}

	.actions {
		background-color: #007aff;
		border-radius: 8rpx;
		padding: 10rpx;
		display: flex;
		justify-content: space-around;
	}

	.container_btn {
		display: flex;
		flex-direction: column;
		padding: 70px;
	}

	.function-bar {
		display: flex;
		justify-content: space-around;
		align-items: center;
		background-color: #007aff;
		border-radius: 30px;
		padding: 12px 12px;
		position: relative;
	}

	.function-btn {
		display: flex;
		flex-direction: column;
		align-items: center;
		cursor: pointer;
	}

	.btn-text {
		font-size: 12px;
		margin-top: 5px;
	}

	.more-list {
		background-color: #ffffff;
		border-radius: 12px;
		margin-left: 40px;
		margin-right: 40px;
	}

	.list-item {
		padding: 8px;
		/* border-bottom: 1px solid #ddd; */
		cursor: pointer;
		font-size: 15px;
	}
</style>